package com.sduept.nwld.dataserver.controller.base.primary;

import com.sduept.bigdata.fault.system.properties.FaultSystemProperties;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.bean.RequestScoped;
import javax.inject.Named;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

@Named
@RequestScoped
public class SvgViewController extends AbstractController {
	private static final long serialVersionUID = 4385196712859462787L;
	@Autowired
	private FaultSystemProperties pros;
	private String svgContent;
	
	@PostConstruct
	private void init(){
		String sid = getParameter("stationId");
		String stype = getParameter("svgType");
		if(sid != null){
			genSvgContent(sid,stype);
		}
	}
	
	private void genSvgContent(String stationId,String type){
		StringBuffer sb = new StringBuffer();
		String svgdir = "2".equals(type) ? pros.getSvgBxPath() : pros.getSvgEmsPath();
		File sf = new File(svgdir+stationId+".svg");
		if(sf.exists()){
			RandomAccessFile raf = null;
			try {
				raf = new RandomAccessFile(sf, "r");
				String lstr = raf.readLine();
				boolean startAdd = false;
				while(lstr != null){
					if(startAdd){
						lstr = new String(lstr.trim().getBytes("ISO-8859-1"), "utf-8");
						lstr = lstr.replaceAll("\"", "'");
//						if(lstr.startsWith("<text")){
//							lstr = lstr.replaceFirst("<text", "<text onclick='alert(this)' ");
//						}
						sb.append(lstr);
					} else {
						if(lstr.startsWith("<svg")){
							startAdd = true;
							lstr = new String(lstr.trim().getBytes("ISO-8859-1"), "utf-8");
							lstr = lstr.replaceAll("\"", "'");
							sb.append(lstr);
						}
					}
					lstr = raf.readLine();
				}
				svgContent = sb.toString();
			} catch (Exception e) {
				e.printStackTrace();
			} finally{
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
	}
	
	public void renameBxSvg(){/*
		File svgdir = new File("H:\\项目管理\\南网大数据\\data\\bx\\bhsvg");
		File[] fs = svgdir.listFiles();
		List<?> bxs = dao.nativeQuery("select stationID,ems_cim_id from t_bx_substation");
		for(Object o : bxs){
			Object[] os = (Object[]) o;
			for (File file : fs) {
				if(file.getName().contains(os[0].toString()) && os[1] != null){
					file.renameTo(new File("E:\\aaa\\bxsvg\\"+os[1].toString()+".svg"));
					log.info("rename "+os[0].toString());
					break;
				}
			}
		}
	*/}
	public String getSvgContent() {
		return svgContent;
	}
	public void setSvgContent(String svgContent) {
		this.svgContent = svgContent;
	}
	
}
